package com.hontech.bv.task

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import kotlinx.coroutines.CompletableDeferred

class TaskThread(name: String) : HandlerThread(name) {

    init {
        start()
    }
}

object AppTask : Handler(Looper.getMainLooper())

class PromiseTask<T>(val cb: () -> T) : Runnable {

    private val promise = CompletableDeferred<T>()

    fun exec(task: Handler): PromiseTask<T> {
        task.post(this)
        return this
    }

    suspend fun await() = promise.await()

    suspend fun await(timeout: Long) = promise.await(timeout)

    override fun run() {

        try {
            val value = cb()
            promise.complete(value)
        } catch (e: Exception) {
            promise.completeExceptionally(e)
        }
    }
}

